package com.ac.scum.log.web.utils.user;

import com.ac.common.core.exception.BaseException;
import com.ac.common.core.exception.config.ExceptionType;
import com.ac.scum.log.bean.AdminUser;
import com.ac.scum.log.web.dto.login.LoginDTO;
import com.ac.scum.log.web.model.login.service.JWTUtil;
import com.ac.scum.log.web.model.user.mapper.AdminUserMapper;
import com.ac.scum.log.web.utils.spring.SpringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class CurrentUserUtil {


    public static String getCurrentToken() throws BaseException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            String token = attributes.getRequest().getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                return token.substring(7);
            }
        }
        throw new BaseException(ExceptionType.System_Error);
    }

    public static String getCurrentLoginUserPhone() throws BaseException {
        return (String) JWTUtil.parseClaim(getCurrentToken()).getPayload().get("phone");
    }

    public static AdminUser getCurrentLogUser() throws BaseException {
        return SpringUtils.getBean(AdminUserMapper.class).findUserByPhone(getCurrentLoginUserPhone());
    }

    public static LoginDTO getCurrentLoginDTO() throws BaseException {
        RedisTemplate<String, Object> redisTemplate = SpringUtils.getBean("redisTemplate");
        return (LoginDTO) redisTemplate.opsForValue().get(getCurrentToken());
    }

    public static Long getCurrentServerId() throws BaseException {
        return getCurrentLoginDTO().getUserPreference().getLastCheckServerId();
    }
}
